package cron

import (
	"fmt"
	"time"
	"reflect"

	"e4ting/internal/svc"

	. "github.com/go-co-op/gocron/v2"
)

var (
	// cron = Cron{}
	scheduler Scheduler
	body = reflect.TypeOf(Cron{})
	fn_fuse reflect.Value
)

func init(){

	fmt.Println("初始化定时任务")


	// 确保传入的参数是一个结构体
	if body.Kind() != reflect.Struct {
		fmt.Println("Input is not a struct")
		return
	}
	// fmt.Println("函数总数", t.NumMethod())
	// 遍历结构体的字段并打印名称
	for i := 0; i < body.NumMethod(); i++ {
		field := body.Method(i)
		fmt.Println("可注册函数: 1 * * * * * ", field.Name)
	}
}

func AddTask(s Scheduler, schedule string, callName string) {
	in := make([]reflect.Value, 0)
	function := fn_fuse.MethodByName(callName)

	job, err := s.NewJob(
		CronJob(
			// standard cron tab parsing
			schedule,
			true,
		),
		NewTask(
			func() {
				// fmt.Printf("测试运行\n")
				ret := function.Call(in)  // [0].Interface()
				for _,out := range ret{
					fmt.Printf("%+v", out.Interface())
				}
			},
		),
	)
	fmt.Printf("+ [%v] 定时任务 %s => %s %v\n", job.ID(), schedule, callName, err)
	// fmt.Printf("+ 任务id : %v %v\n", job.ID(), err)
}

func Start(crontab [][]string, svcCtx *svc.ServiceContext){
	fn_fuse = reflect.ValueOf(&Cron{Ctx:svcCtx})
	scheduler, _ = NewScheduler(WithLocation(time.Local))
	// defer func() { _ = s.Shutdown() }()
	for _,item := range crontab{
		schedule,callName := item[0],item[1]
		AddTask(scheduler, schedule, callName)
	}
	scheduler.Start()
}
